package com.zh.mp.demo.modules.demo.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.zh.mp.demo.constants.Consts;
import com.zh.mp.demo.constants.KafkaConsts;
import com.zh.mp.demo.exception.NotFoundException;
import com.zh.mp.demo.modules.demo.entity.Email;
import com.zh.mp.demo.modules.demo.entity.User;
import com.zh.mp.demo.modules.demo.service.IUserService;
import com.zh.mp.demo.modules.demo.service.MailService;
import com.zh.mp.demo.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-09-27
 */
@Slf4j
@RestController
@RequestMapping("/person")
public class PersonController {

    @Value("${spring.servlet.multipart.location}")
    private String fileTempPath;

    private final IUserService userService;

    private final MailService mailService;

    private final Producer producer;

    private final KafkaTemplate kafkaTemplate;

    @Autowired
    public PersonController(IUserService userService, MailService mailService, Producer producer, KafkaTemplate  kafkaTemplate){
        this.userService = userService;
        this.mailService = mailService;
        this.producer = producer;
        this.kafkaTemplate = kafkaTemplate;
    }

    @GetMapping(value = {"", "/"})
    public String index(HttpSession session)
    {
        String str = (String) session.getAttribute(Consts.SESSION_KEY);
        return str;
    }

    @PostMapping("/token")
    public Object token(User user, HttpSession session) throws UnsupportedEncodingException {
        Map<String,Object> params = new HashMap<String,Object>();
        User dbUser = userService.getById(12L);
        if (dbUser.getName().equals(user.getName())) {
            String token = JwtUtil.createToken(dbUser);
            session.setAttribute(Consts.SESSION_KEY, token);
            log.info("token {}", token);
            params.put("token", token);
        }else{
            params.put("token", "");
        }
        return params;
    }

    @RequestMapping(value = "/sendMail")
    public Email sendEmail() {
        Email email_email = new Email();
        List<String> addressList = new ArrayList<String>();
        addressList.add("314893771@qq.com");
        email_email.setToAddress(addressList);
        email_email.setSubject("java碎碎念-主题测试");// 主题
        email_email.setContent("你好！<br><br> 测试邮件发送成功！");
        // 发送邮件
        mailService.sendMail(email_email);

        return email_email;
    }

    @RequestMapping("/getCode")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = producer.createText();
        log.info("******************验证码是: " + capText + "******************");
        // store the text in the session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text
        BufferedImage bi = producer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public List local(@RequestParam("files") MultipartFile[] files) {
        List<Object> localFilePaths = new ArrayList<>();
        log.info("数组的长度 {}", files.length);
        for (MultipartFile file:files) {
            if (file.isEmpty()) {
                continue;
            }
            String fileName = file.getOriginalFilename();
            String rawFileName = StrUtil.subBefore(fileName, ".", true);
            String fileType = StrUtil.subAfter(fileName, ".", true);
            String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current() + "." + fileType;
            try {
                file.transferTo(new File(localFilePath));
                Dict dict = Dict.create();
                dict.set("fileName", fileName).set("filePath", localFilePath);
                localFilePaths.add(dict);
            } catch (IOException e) {
                throw new NotFoundException(500L, "文件上传失败");
            }
        }

        kafkaTemplate.send(KafkaConsts.TOPIC_TEST, new JSONArray(localFilePaths));

        return localFilePaths;
    }
}
